package org.example.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.executor.ResultExtractor;
import org.example.Contant.BusinessException;
import org.example.Contant.Result;
import org.example.dto.UpdateUserDto;
import org.example.dto.UserDto;
import org.example.entity.User;
import org.example.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Controller
@RequestMapping("/api")
public class AccountController {

    @Autowired
    private AccountService accountService;

    //获取账户管理页面数据（用户列表和当前用户信息）
    @GetMapping("/account")
    public String account(){
        return "account";
    }

    //添加新用户
    @PostMapping("/admin/add")
    @ResponseBody
    public Result<String> addUser(@RequestBody UserDto userDto){
        int add = accountService.add(userDto);
        if (add != 1){
            throw new BusinessException("500","插入失败");
        }
        return Result.success("200","添加成功");
    }

    //查询所有用户
    @GetMapping("/admin/list")
    @ResponseBody
    public List<UserDto> getAllUsers(){
        return accountService.getAllUsers();
    }


    //删除用户
    @DeleteMapping("/admin/delete/{id}")
    @ResponseBody
    public Result<String> deleteUser(@PathVariable("id") Long id){
        int i = accountService.deleteUserById(id);
        if (i != 1){
            throw new BusinessException("500","删除失败");
        }
        return Result.success("200","删除成功");
    }

    //更新用户信息
    @PutMapping("/admin/update")
    @ResponseBody
    public void updateUserByAdmin(@RequestBody UserDto userDto){
        accountService.update(userDto);
    }

    //更新用户信息
    @PutMapping("/account/update")
    @ResponseBody
    public Result<String> updateUserByUser(@RequestBody UpdateUserDto user){
        int i = accountService.updateByUser(user);
        if (i != 1){
            throw new BusinessException("500","更新错误");
        }
        return Result.success("200","更新成功");
    }


}
